import * as echarts from '../components/ec-canvas/echarts';
var http = require('../../script/api.js');
import {
  parseTime,
  getRandomColor
} from '../../utils/util';
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    key: {
      type: Number,
      value: 0
    },
  },
  observers: {
    'key': function (val) {
      if (val != null && val > 0) {
        this.getSumInfo();
        this.getOrderRankData();
        this.getOrderTypeData();
        this.getOrderPregressData();
        this.getOrderTrendData();
      }
    }
  },
  lifetimes: {
    created: function () {
      this.getLastSevenDays();
      this.setDefultDate();
      this.getSumInfo();
    },
    attached: function () {
      this.getOrderRankData();
    },
    ready: function () {
      this.ecComponent_ordertype = this.selectComponent('#ordertype-chart-dom');
      this.initOrderTypeChart();
      this.getOrderTypeData();

      this.ecComponent_orderprogress = this.selectComponent('#orderprogress-chart-dom');
      this.initOrderPregressChart();
      this.getOrderPregressData();

      this.ecComponent_orderTrend = this.selectComponent('#ordertrend-chart-dom');
      this.initOrderTrendChart();
      this.getOrderTrendData();
    },
    detached: function () {
      if (this.chart_ordertype) {
        this.chart_ordertype.dispose();
        this.chart_ordertype = null;
      }
      if (this.chart_orderprogress) {
        this.chart_orderprogress.dispose();
        this.chart_orderprogress = null;
      }
      if (this.chart_orderTrend) {
        this.chart_orderTrend.dispose();
        this.chart_orderTrend = null;
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    BeginTime: '',
    EndTime: '',
    PopShow: false,
    date_s: '',
    date_e: '',
    dateStart: '',
    dateEnd: '',
    searchType: 'today',
    sumInfo: {
      TotalCount: 0,
      ToDoCount: 0,
      ExpireCount: 0,
      ReminderCount: 0,
      FinishCount: 0,
      FinishRateStr: '--'
    },
    rankMode: 1,
    RankList: [],
    RankListRegion: [], // 区域
    RankListStation: [], // 部门
    RankListArea: [], // 小区
    noRankData: false,
    sort: 'asc',
    ecOrdertype: {
      lazyLoad: true
    },
    orderTypeData: [],
    ecOrderprogress: {
      lazyLoad: true
    },
    color: ['#01e1fb', '#00a8ff', '#3270ff', '#40e1d1', '#ff9900', '#ff6600', '#ff0000'],
    color1: [
      "#FAE927",
      "#E9E416",
      "#C9DA36",
      "#9ECB3C",
      "#6DBC49",
      "#37B44E",
      "#3DBA78",
      "#14ADCF",
      "#209AC9",
      "#1E91CA",
      "#2C6BA0",
      "#2B55A1",
      "#2D3D8E",
      "#44388E",
      "#6A368B",
      "#7D3990",
      "#A63F98",
      "#C31C88",
      "#D52178",
      "#D5225B",
      "#D02C2A",
      "#D44C2D",
      "#F57A34",
      "#FA8F2F",
      "#D99D21",
      "#CF7B25",
      "#CF7B25",
      "#CF7B25",
    ],
    orderProgressData: [],
    ecOrderTrend: {
      lazyLoad: true
    },
    orderTrendData: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /******************** 选择时间 ****************/
    setDefultDate() {
      const date = new Date();
      const date_e = date.getTime();
      const dateEnd = parseTime(date, 'yyyy-MM-dd');
      date.setDate(date.getDate() - 6);
      const dateStart = parseTime(date, 'yyyy-MM-dd');
      const date_s = date.getTime();
      this.setData({
        date_s,
        dateStart: dateStart,
        dateEnd: dateEnd,
        date_e
      });
    },
    openDatePop(e) {
      var type = e.currentTarget.dataset.type;
      this.setData({
        [type + 'Pop']: true
      });
    },
    closeDatePop() {
      this.setData({
        DateS_Pop: false,
        DateE_Pop: false
      });
    },
    onInput_S(e) {
      this.setData({
        date_s: e.detail,
      });
    },
    onConfirm_S(e) {
      this.setData({
        DateS_Pop: false,
        dateStart: parseTime(this.data.date_s, 'yyyy-MM-dd')
      });
      this.doSearch();
    },
    onInput_E(e) {
      this.setData({
        date_e: e.detail,
      });
    },
    onConfirm_E(e) {
      this.setData({
        DateE_Pop: false,
        dateEnd: parseTime(this.data.date_e, 'yyyy-MM-dd')
      });
      this.doSearch();
    },
    /******************** 选择时间 ****************/
    /******************** 工单概览 ****************/
    getLastSevenDays() {
      const date = new Date();
      const dateEnd = parseTime(date, 'yyyy-MM-dd hh:mm:ss');
      date.setDate(date.getDate() - 6);
      const dateStart = parseTime(date, 'yyyy-MM-dd hh:mm:ss');
      this.setData({
        BeginTime: dateStart,
        EndTime: dateEnd,
      })
    },
    getSearchTime() {
      const now = new Date();
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };
      switch (this.data.searchType) {
        case 'today':
          const startOfDay = new Date(now);
          startOfDay.setHours(0, 0, 0, 0);
          return {
            start: formatDate(startOfDay),
              end: formatDate(now)
          };
        case 'yesterday':
          const yesterday = new Date(now);
          yesterday.setDate(now.getDate() - 1);
          yesterday.setHours(0, 0, 0, 0);
          const endOfYesterday = new Date(yesterday);
          endOfYesterday.setHours(23, 59, 59, 999);
          return {
            start: formatDate(yesterday),
              end: formatDate(endOfYesterday)
          };
        case 'thisWeek':
          const weekDay = now.getDay();
          const mondayOffset = weekDay === 0 ? -6 : 1 - weekDay; // 周一偏移量
          const startOfWeek = new Date(now);
          startOfWeek.setDate(now.getDate() + mondayOffset);
          startOfWeek.setHours(0, 0, 0, 0);
          // const endOfWeek = new Date(startOfWeek);
          // endOfWeek.setDate(startOfWeek.getDate() + 6);
          // endOfWeek.setHours(23, 59, 59, 999);
          return {
            start: formatDate(startOfWeek),
              end: formatDate(now)
          };
        case 'lastWeek':
          const lastWeekStart = new Date(now);
          lastWeekStart.setDate(now.getDate() - now.getDay() - 6);
          lastWeekStart.setHours(0, 0, 0, 0);
          const lastWeekEnd = new Date(lastWeekStart);
          lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
          lastWeekEnd.setHours(23, 59, 59, 999);
          return {
            start: formatDate(lastWeekStart),
              end: formatDate(lastWeekEnd)
          };
        case 'thisMonth':
          const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
          // const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
          return {
            start: formatDate(startOfMonth),
              end: formatDate(now)
          };
        case 'lastMonth':
          const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1, 0, 0, 0);
          const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59);
          return {
            start: formatDate(startOfLastMonth),
              end: formatDate(endOfLastMonth)
          };
        default:
          throw new Error('Invalid time range type');
      }
    },
    orderTabChange(e) {
      this.setData({
        searchType: e.currentTarget.dataset.type
      });
      this.getSumInfo();
    },
    getSumInfo() {
      // const date = this.getSearchTime();
      const params = {
        ReportType: 21,
        ReportParam: JSON.stringify({
          BeginTime: this.data.dateStart,
          EndTime: this.data.dateEnd,
        })
      }
      http.GetOrderReport(params).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.setData({
              sumInfo: {
                TotalCount: res.data.TotalCount,
                ToDoCount: res.data.ToDoCount,
                ExpireCount: res.data.ExpireCount,
                ReminderCount: res.data.ReminderCount,
                FinishCount: res.data.FinishCount,
                FinishRateStr: res.data.FinishRateStr || ''
              }
            })
          }
        } else {
          this.setData({
            TotalCount: 0,
            ToDoCount: 0,
            ExpireCount: 0,
            ReminderCount: 0,
            FinishCount: 0,
            FinishRateStr: '--'
          });
        }
      })
    },
    /******************** 工单概览 ****************/
    /************* 工单完成率排行榜 ***************/
    rankModeChange: function (e) {
      const index = parseInt(e.currentTarget.dataset.index);
      this.setData({
        rankMode: index
      });
      this.setRankData();
    },
    setRankData() {
      const index = this.data.rankMode;
      let list = []
      if (index === 1) {
        list = this.data.RankListRegion;
      } else if (index === 2) {
        list = this.data.RankListStation;
      } else if (index === 3) {
        list = this.data.RankListArea;
      }
      const noData = list.length === 0;
      this.setData({
        RankList: list,
        noRankData: noData
      });
    },
    getOrderRankData() {
      this.data.loading = true;
      const params = {
        ReportType: 10,
        ReportParam: this.data.sort === "asc"
      };
      http.GetOrderReport(params).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.setData({
              RankListRegion: res.data.regionData,
              RankListStation: res.data.stationData,
              RankListArea: res.data.areaData
            });
            this.setRankData();
          }
        } else {
          this.setData({
            RankListRegion: [],
            RankListStation: [],
            RankListArea: [],
            RankList: [],
            noRankData: false
          });
        }
        this.data.loading = false;
      })
    },
    sortHandle() {
      if (this.data.loading) return;
      this.setData({
        sort: this.data.sort === 'desc' ? 'asc' : 'desc'
      });
      this.getOrderRankData();
    },
    /************* 工单完成率排行榜 ***************/


    /*************** 工单类型分析 ****************/
    getOrderTypeData() {
      const params = {
        ReportType: 13,
        ReportParam: JSON.stringify({
          IsWaiPai: 1,
          BeginTime: this.data.BeginTime,
          EndTime: this.data.EndTime,
        })
      }
      http.GetOrderReport(params).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.length > 0) {
            const list = [];
            let total = 0;
            for (let i = 0; i < res.data.length - 2; i++) {
              total += res.data[i].SubOrderTypeCount;
              list.push({
                name: res.data[i].SubOrderTypeName,
                value: res.data[i].SubOrderTypeCount,
              })
            }
            for (var j = 0; j < list.length; j++) {
              list[j].rate = total === 0 ? 0 : ((list[j].value / total) * 100).toFixed(2);
            }
            this.setData({
              orderTypeData: list
            });
            this.setOrderTypeChartOption();
          }
        }
      })
    },
    initOrderTypeChart() {
      this.ecComponent_ordertype.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_ordertype = chart;
        this.setOrderTypeChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setOrderTypeChartOption() {
      if (!this.data.orderTypeData || this.data.orderTypeData.length === 0) {
        // noData.value = true;
        return;
      }
      // noData.value = false;

      const resData = [...this.data.orderTypeData];
      const data = [];
      resData.forEach((item) => {
        data.push({
          value: item.value,
          name: item.name,
        });
      });
      data.sort((a, b) => b.value - a.value);
      const option = {
        color: this.data.color1,
        legend: {
          show: false,
          orient: "vertical",
          left: "0",
          top: "middle",
          itemWidth: 20,
          itemHeight: 15,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
          formatter: (name) => {
            const item = data.find(i => i.name === name);
            return name + ' ' + item.value;
          }
        },
        calculable: true,
        tooltip: {
          trigger: 'item',
          valueFormatter: function (val) {
            return val + " 单";
          },
          textStyle: {
            color: "#313131",
            fontSize: 13,
          },
          confine: true,
        },
        series: [{
            name: "工单类型",
            type: "pie",
            startAngle: 0,
            clockwise: false,
            radius: ["20%", "100%"],
            center: ["50%", "50%"],
            roseType: "area",
            avoidLabelOverlap: false,
            padAngle: 1,
            label: {
              show: false,
              position: "inside",
              formatter: "{c}",
              textStyle: {
                color: "#fff",
                fontSize: 13,
              },
            },
            itemStyle: {
              borderRadius: 6,
            },
            data: data,
          },
          {
            type: "pie",
            radius: '12%',
            data: [100],
            center: ["65%", "50%"],
            itemStyle: {
              color: "#E83A30",
            },
            hoverAnimation: false,
            label: {
              show: false,
            },
            tooltip: {
              show: false
            },
          },
        ],
      };
      this.chart_ordertype.setOption(option);
    },
    /*************** 工单类型分析 ****************/


    /*************** 工单进度分析 ****************/
    getOrderPregressData() {
      const params = {
        ReportType: 12,
        ReportParam: JSON.stringify({
          BeginTime: this.data.BeginTime,
          EndTime: this.data.EndTime,
        })
      }
      http.GetOrderReport(params).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.length > 0) {
            const sumRow = res.data[res.data.length - 1];
            const total = sumRow.SubOrderTypeCount;
            const list = [{
                "name": "已完工",
                "value": sumRow.FinishCount,
                "rate": ((sumRow.FinishCount / total) * 100).toFixed(2)
              },
              {
                "name": "未接收",
                "value": sumRow.ReceiveCount,
                "rate": ((sumRow.ReceiveCount / total) * 100).toFixed(2)
              },
              {
                "name": "处理中",
                "value": sumRow.HandleCount,
                "rate": ((sumRow.HandleCount / total) * 100).toFixed(2)
              },
              {
                "name": "已重发",
                "value": sumRow.ReSendCount,
                "rate": ((sumRow.ReSendCount / total) * 100).toFixed(2)
              }
            ];

            this.setData({
              orderProgressData: list
            });
            this.setOrderProgressChartOption();
          }
        }
      })
    },
    initOrderPregressChart() {
      this.ecComponent_orderprogress.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_orderprogress = chart;
        this.setOrderProgressChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setOrderProgressChartOption() {
      if (this.data.orderProgressData.length === 0) return;
      const resData = [...this.data.orderProgressData];
      var data = [];
      for (var i = 0; i < resData.length; i++) {
        data.push({
          name: resData[i].name,
          value: resData[i].value,
        });
      }
      const option = {
        grid: {
          top: "0",
          left: "10",
          right: "10",
          bottom: "10",
          containLabel: true,
        },
        color: this.data.color,
        title: {
          text: "工单进度",
          top: "middle",
          left: "center",
          textStyle: {
            color: "#606266",
            fontSize: 12,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: 'item',
          valueFormatter: function (val) {
            return val + " 单";
          },
          textStyle: {
            color: "#313131",
            fontSize: 13,
          },
          confine: true,
        },
        legend: {
          show: false,
          orient: "vertical",
          right: "20",
          top: "middle",
          itemWidth: 20,
          itemHeight: 15,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
        },
        toolbox: {
          show: false,
        },
        series: {
          name: "工单进度",
          type: "pie",
          clockWise: false,
          radius: ["45%", "70%"],
          center: ["50%", "50%"],
          hoverAnimation: true,
          avoidLabelOverlap: false,
          padAngle: 3,
          label: {
            show: false,
            formatter: "{d}%",
            // formatter: "{b|{b}}\n{d|{d}%}",
            // rich: {
            //   b: {
            //     fontSize: 12,
            //     color: "#606266",
            //     align: "left",
            //     width: "100%",
            //   },
            //   d: {
            //     fontSize: 14,
            //     color: "#606266",
            //     align: "left",
            //   },
            // },
          },
          itemStyle: {
            borderRadius: 6,
          },
          data: data,
        },
      };
      this.chart_orderprogress.setOption(option);
    },
    /*************** 工单进度分析 ****************/

    /*************** 工单趋势分析 ****************/
    getOrderTrendData() {
      const params = {
        ReportType: 22,
        ReportParam: JSON.stringify({
          BeginTime: this.data.BeginTime,
          EndTime: this.data.EndTime,
        })
      }
      http.GetOrderReport(params).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.length > 0) {
            this.setData({
              orderTrendData: res.data
            });
            this.setOrderTrendChartOption();
          }
        }
      })
    },
    initOrderTrendChart: function () {
      this.ecComponent_orderTrend.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_orderTrend = chart;
        this.setOrderTrendChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setOrderTrendChartOption() {
      if (this.data.orderTrendData.length === 0) return;
      const resData = [...this.data.orderTrendData];
      let xData = [];
      let yData1 = [];
      let yData2 = [];
      for (let i = 0; i < resData.length; i++) {
        const item = resData[i];
        xData.push(item.DateStr);
        yData1.push(item.TotalCount);
        yData2.push(item.FinishCount);
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            textShadowBlur: 0,
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          // renderMode: 'richText',
          valueFormatter: function (val) {
            return val + " 单";
          },
        },
        legend: {

        },
        grid: {
          top: '50',
          right: '40',
          left: '10',
          bottom: '30',
          containLabel: true,
        },
        xAxis: [{
          type: 'category',
          // boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            formatter: (val) => {
              return val.slice(5, 10)
            }
          },
          data: xData,
          axisPointer: {
            type: 'shadow'
          }
        }],
        yAxis: [{
          type: 'value',
          name: '数量（单）',
          axisLine: {
            show: true,
          },
          axisLabel: {

          }
        }],
        series: [{
            name: '工单总数',
            type: 'bar',
            data: yData1,
            barMaxWidth: 10,
            markPoint: {
              data: [{
                  type: 'max',
                  name: 'Max'
                },
                {
                  type: 'min',
                  name: 'Min'
                }
              ]
            },
            markLine: {
              data: [{
                type: 'average',
                name: 'Avg'
              }]
            }
          },
          {
            name: '完成数',
            type: 'bar',
            data: yData2,
            barMaxWidth: 10,
            markPoint: {
              data: [{
                  type: 'max',
                  name: 'Max'
                },
                {
                  type: 'min',
                  name: 'Min'
                }
              ]
            },
            markLine: {
              data: [{
                type: 'average',
                name: 'Avg'
              }]
            }
          }
        ]
      }
      this.chart_orderTrend.setOption(option);
    },
    /*************** 工单趋势分析 ****************/
  }
})